package com.wiselink.naver;

import com.alibaba.fastjson2.JSONObject;
import com.wiselink.exception.NaverException;
import com.wiselink.common.utils.StringUtils;
import lombok.Getter;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCrypt;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 获取naver-token
 */
public class GetToken {
    private static final Logger log = LoggerFactory.getLogger(GetToken.class);

    @Getter
    public static class TokenVO {
        private final String token;
        private final Integer expireIn;

        public TokenVO(String token,
                       Integer expireIn) {
            this.token = token;
            this.expireIn = expireIn;
        }
    }

    /**
     * 获取naver-token
     *
     * @param clientId     naver店铺Key
     * @param clientSecret naver店铺秘钥
     * @param accountId    naver账号
     * @return token
     */
    public static TokenVO execute(String clientId, String clientSecret, String accountId) throws IOException {
        if (StringUtils.isEmpty(clientId)
                || StringUtils.isEmpty(clientSecret)
                || StringUtils.isEmpty(accountId)) {
            throw new IllegalArgumentException("get naver token 参数不全");
        }
        OkHttpClient client = new OkHttpClient();
        Long timestamp = System.currentTimeMillis();
        Map<String, Object> map = new HashMap<>();
        map.put("client_id", clientId);
        map.put("timestamp", timestamp);
        map.put("grant_type", "client_credentials");
        map.put("client_secret_sign", generateSignature(clientId, clientSecret, timestamp));
        map.put("type", "SELF");
        map.put("account_id", accountId);

        // 使用 FormBody.Builder 构建表单数据
        FormBody.Builder formBuilder = new FormBody.Builder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            formBuilder.add(entry.getKey(), entry.getValue().toString());
        }
        Request request = new Request.Builder()
                .url("https://api.commerce.naver.com/external/v1/oauth2/token")
                .post(formBuilder.build())
                .header("Content-Type", "application/x-www-form-urlencoded")
                .build();

        try (Response response = client.newCall(request).execute()) {
            int code = response.code();
            log.info("code {}", response.code());
            String result = Objects.requireNonNull(response.body()).string();
            log.info("获取token resp: {}", result);
            if (code == 200) {
                // {"access_token":"xxxx","expires_in":10131,"token_type":"Bearer"}
                JSONObject object = JSONObject.parseObject(result);
                String token = object.getString("token_type") + " " + object.getString("access_token");
                int expiresIn = object.getIntValue("expires_in");
                return new TokenVO(token, expiresIn);
            }
            throw new NaverException("获取naver-token fail: " + result);
        } catch (IOException e) {
            log.error("获取token fail: {}", e.getMessage(), e);
            throw new IOException("获取token fail: " + e.getMessage());
        }
    }

    private static String generateSignature(String clientId, String clientSecret, Long timestamp) {
        // 밑줄로 연결하여 password 생성
        String password = StringUtils.joinWith("_", clientId, timestamp);
        // bcrypt 해싱
        String hashedPw = BCrypt.hashpw(password, clientSecret);
        // base64 인코딩
        return Base64.getUrlEncoder().encodeToString(hashedPw.getBytes(StandardCharsets.UTF_8));
    }
}
